from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework.permissions import AllowAny, IsAuthenticated
from django.contrib.auth.models import User
from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth import authenticate
from .user_profile_models import UserProfile
from django.conf import settings
import os


@api_view(['POST'])
@permission_classes([AllowAny])
def register(request):
    """用户注册"""
    username = request.data.get('username')
    password = request.data.get('password')
    email = request.data.get('email', '')
    
    if not username or not password:
        return Response({
            'error': '用户名和密码不能为空'
        }, status=status.HTTP_400_BAD_REQUEST)
    
    if User.objects.filter(username=username).exists():
        return Response({
            'error': '用户名已存在'
        }, status=status.HTTP_400_BAD_REQUEST)
    
    # 创建用户
    user = User.objects.create_user(
        username=username,
        password=password,
        email=email
    )
    
    # 生成token
    refresh = RefreshToken.for_user(user)
    
    return Response({
        'message': '注册成功',
        'user': {
            'id': user.id,
            'username': user.username,
            'email': user.email,
        },
        'tokens': {
            'access': str(refresh.access_token),
            'refresh': str(refresh),
        }
    }, status=status.HTTP_201_CREATED)


@api_view(['POST'])
@permission_classes([AllowAny])
def login(request):
    """用户登录"""
    username = request.data.get('username')
    password = request.data.get('password')
    
    if not username or not password:
        return Response({
            'error': '用户名和密码不能为空'
        }, status=status.HTTP_400_BAD_REQUEST)
    
    user = authenticate(username=username, password=password)
    
    if user is None:
        return Response({
            'error': '用户名或密码错误'
        }, status=status.HTTP_401_UNAUTHORIZED)
    
    # 生成token
    refresh = RefreshToken.for_user(user)
    
    return Response({
        'message': '登录成功',
        'user': {
            'id': user.id,
            'username': user.username,
            'email': user.email,
        },
        'tokens': {
            'access': str(refresh.access_token),
            'refresh': str(refresh),
        }
    })


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def current_user(request):
    """获取当前登录用户信息"""
    user = request.user
    profile = user.profile
    
    avatar_url = None
    if profile.avatar:
        avatar_url = request.build_absolute_uri(profile.avatar.url)
    
    return Response({
        'id': user.id,
        'username': user.username,
        'email': user.email,
        'is_staff': user.is_staff,
        'is_superuser': user.is_superuser,
        'avatar': avatar_url,
        'phone': profile.phone,
        'department': profile.department,
        'position': profile.position,
    })


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def logout(request):
    """用户登出"""
    try:
        refresh_token = request.data.get('refresh')
        if refresh_token:
            token = RefreshToken(refresh_token)
            token.blacklist()
        return Response({'message': '登出成功'})
    except Exception as e:
        return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)


@api_view(['PUT'])
@permission_classes([IsAuthenticated])
def update_profile(request):
    """更新用户基本资料"""
    user = request.user
    profile = user.profile
    
    # 更新用户基本信息
    email = request.data.get('email')
    if email and email != user.email:
        if User.objects.filter(email=email).exclude(id=user.id).exists():
            return Response({'error': '该邮箱已被使用'}, status=status.HTTP_400_BAD_REQUEST)
        user.email = email
        user.save()
    
    # 更新扩展资料
    phone = request.data.get('phone')
    department = request.data.get('department')
    position = request.data.get('position')
    
    if phone is not None:
        profile.phone = phone
    if department is not None:
        profile.department = department
    if position is not None:
        profile.position = position
    
    profile.save()
    
    return Response({
        'message': '资料更新成功',
        'user': {
            'username': user.username,
            'email': user.email,
            'phone': profile.phone,
            'department': profile.department,
            'position': profile.position,
        }
    })


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def upload_avatar(request):
    """上传头像"""
    user = request.user
    profile = user.profile
    
    if 'avatar' not in request.FILES:
        return Response({'error': '请选择要上传的图片'}, status=status.HTTP_400_BAD_REQUEST)
    
    avatar_file = request.FILES['avatar']
    
    # 检查文件大小（限制5MB）
    if avatar_file.size > 5 * 1024 * 1024:
        return Response({'error': '图片大小不能超过5MB'}, status=status.HTTP_400_BAD_REQUEST)
    
    # 检查文件类型
    allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
    if avatar_file.content_type not in allowed_types:
        return Response({'error': '只支持JPG、PNG、GIF、WEBP格式的图片'}, status=status.HTTP_400_BAD_REQUEST)
    
    # 删除旧头像
    if profile.avatar:
        old_avatar_path = profile.avatar.path
        if os.path.exists(old_avatar_path):
            os.remove(old_avatar_path)
    
    # 保存新头像
    profile.avatar = avatar_file
    profile.save()
    
    avatar_url = request.build_absolute_uri(profile.avatar.url)
    
    return Response({
        'message': '头像上传成功',
        'avatar': avatar_url
    })


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def change_password(request):
    """修改密码"""
    user = request.user
    
    old_password = request.data.get('old_password')
    new_password = request.data.get('new_password')
    
    if not old_password or not new_password:
        return Response({'error': '请输入旧密码和新密码'}, status=status.HTTP_400_BAD_REQUEST)
    
    # 验证旧密码
    if not user.check_password(old_password):
        return Response({'error': '旧密码不正确'}, status=status.HTTP_400_BAD_REQUEST)
    
    # 验证新密码
    if len(new_password) < 6:
        return Response({'error': '新密码长度至少6位'}, status=status.HTTP_400_BAD_REQUEST)
    
    # 设置新密码
    user.set_password(new_password)
    user.save()
    
    return Response({'message': '密码修改成功，请重新登录'})
